
package biblio.dao;


import biblio.domain.Book;
import biblio.exception.NoSuchEntityException;
import java.io.Serializable;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


/**
 * Default implementation of BookDAO.
 * @author mephisto
 */
public class BookDAOImpl extends HibernateDaoSupport implements BookDAO
{

    public void create(Book book)
    {
        //attention persist throws exception!!
        //org.hibernate.PersistentObjectException:
        //detached entity passed to persist: biblio.domain.Category
        getHibernateTemplate().merge(book);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public List<Book> find(Serializable title) throws NoSuchEntityException
    {
        List<Book> res = getHibernateTemplate().findByNamedParam(
                "from Book where title = :title", "title", title);
        if (res.isEmpty())
            throw new NoSuchEntityException("No book under title " + title);
        return res;
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public void update(Book book) throws NoSuchEntityException
    {
        getHibernateTemplate().update(book);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public void delete(Book book)
    {
        getHibernateTemplate().delete(book);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public List<Book> selectAll()
    {
        return getHibernateTemplate().find("from Book");
    }

    public Book getById(Integer id) throws NoSuchEntityException
    {
        Book val = (Book) getHibernateTemplate().get(Book.class, id);
        if (val == null)
            throw new NoSuchEntityException("No Book identified by id: " + id);
        return val;
    }
}
